package com.snail.jj.androiddemos.components;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.snail.jj.androiddemos.R;
import com.snail.jj.androiddemos.bases.BaseActivity;

/**
 * Created by snail on 2017/5/10.
 */

public class ServiceActivity extends BaseActivity implements View.OnClickListener{

    private static final String TAG = "ServiceActivity";

    private Button startButton;
    private Button stopButton;
    private Button bindButton;
    private Button unBindButton;
    private ForeheadService.MyBinder myBinder;

    //匿名类
    private ServiceConnection connection = new ServiceConnection() {
        //Activity与Service建立关联的时候调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG,"onServiceConnected");
            myBinder = (ForeheadService.MyBinder) service;
            myBinder.startDownload();
        }

        //解除关联的时候调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG,"onServiceDisconnected");
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        startButton = (Button) findViewById(R.id.start_Service);
        stopButton = (Button) findViewById(R.id.stop_Service);
        bindButton = (Button) findViewById(R.id.bind_Service);
        unBindButton = (Button) findViewById(R.id.unBind_Service);
        startButton.setOnClickListener(this);
        stopButton.setOnClickListener(this);
        bindButton.setOnClickListener(this);
        unBindButton.setOnClickListener(this);
        Log.i(TAG,TAG + " thread is " + Thread.currentThread().getName() + Thread.currentThread().getId());
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_Service:
                Intent startIntent = new Intent(this,ForeheadService.class);
                startService(startIntent);
                break;
            case R.id.stop_Service:
                Intent stopIntent = new Intent(this,ForeheadService.class);
                stopService(stopIntent);
                break;
            case R.id.bind_Service:
                Intent bindIntent = new Intent(this,ForeheadService.class);
                bindService(bindIntent,connection,BIND_AUTO_CREATE);
                break;
            case R.id.unBind_Service:
                unbindService(connection);
                break;
            default:
                break;
        }
    }
}
